# -*- coding: utf-8 -*-
"""
@Time ： 2020/11/11 21:10
@Auth ： Mr. William 1052949192
@Company ：特斯汀学院 @testingedu.com.cn
@Function ：app自动化的关键字
"""
import json
import os
import threading
import time

from appium import webdriver
from appium.webdriver.common.touch_action import TouchAction


class App:
    """
    APP自动化测试关键字库
    """

    def __init__(self):
        # self.driver = webdriver.Remote("http://localhost:4723/wd/hub")
        self.driver = None
        self.port = '4723'
        pass

    def startappium(self, appium_path=r'E:\Appium', port='4723'):
        """
        使用node启动appium服务
        :param appium_path: appium的安装路径
        :param port: 服务的发布端口
        :return:
        """
        self.port = port
        cmd = "node " + appium_path + r'\resources\app\node_modules\appium\build\lib\main.js -p' + port
        # 改造为使用子线程启动appium服务
        # 创建一个线程，做什么呢？
        # 做target里面函数要做的事情
        th = threading.Thread(target=os.system, args=(cmd,))
        # 子线程开始工作
        th.start()
        time.sleep(5)

    def stopappium(self, port='4723'):
        """
        停止appium服务
        :param port: 需要停止的appium的端口号
        :return:
        """
        cmd = 'netstat -aon | findstr ' + port
        res = os.popen(cmd).read().split('\n')
        res = res[0].split(' ')
        if len(res) > 1:
            pid = res[len(res) - 1]
            cmd = 'taskkill /F /PID ' + pid
            os.system(cmd)
        else:
            print('端口未占用')

    def startapp(self, conf='{}', t='10'):
        """
        启动APP
        :param conf: 连接appium，启动APP的配置，json格式字符串
        '''{
          "platformName": "Android",
          "deviceName": "3e5d55a",
          "appPackage": "com.tencent.mm",
          "appActivity": ".ui.LauncherUI",
          "noReset": true,
          "unicodeKeyboard": true,
          "resetKeyboard": true,
          "automationName": "uiautomator1"
        }'''
        :param t: 启动APP需要等待的时间
        :return:
        """
        conf = conf.replace('\n', '')
        print(conf)
        conf = json.loads(conf)
        print(conf)
        self.driver = webdriver.Remote("http://localhost:%s/wd/hub" % self.port, conf)
        self.driver.implicitly_wait(15)
        time.sleep(float(t))

    def __find_ele(self, locator='None'):
        """
        兼容，accessibility_id，id，xpath的三种定位
        :param locator: 元素的定位器
        :return: 找到的元素
        """
        ele = None
        if locator.find(':id/') > 0:
            ele = self.driver.find_element_by_id(locator)
        elif locator.startswith('/'):
            ele = self.driver.find_element_by_xpath(locator)
        else:
            ele = self.driver.find_element_by_accessibility_id(locator)

        return ele

    def click(self, locator='None', t='0.5'):
        """
        点击元素
        :param locator: 元素定位器
        :param t: 每一个元素点击之前，默认等待0.5s
        :return:
        """
        time.sleep(float(t))
        ele = self.__find_ele(locator)
        ele.click()

    def input(self, locator="None", value='None', t='0.5'):
        """
        在元素输入value
        :param locator: 定位器
        :param value: 需要输入的值
        :param t: 默认等待0.5s
        :return:
        """
        try:
            time.sleep(float(t))
        except:
            time.sleep(0.5)

        ele = self.__find_ele(locator)
        ele.send_keys(value)

    def swipe(self, location1='(1,1)', location2='(100,100)', t='1'):
        """
        滑动
        :param location1: 第一个坐标的起始位置，格式为（x1,y1）
        :param location2: 第二个坐标的起始位置，格式为（x2,y2）
        :return:
        """
        try:
            time.sleep(float(t))
        except:
            time.sleep(1)

        lo1 = eval(location1)
        lo2 = eval(location2)
        TouchAction(self.driver).press(x=lo1[0], y=lo1[1]).move_to(x=lo2[0], y=lo2[1]).release().perform()

    def sleep(self, t='1'):
        time.sleep(float(t))

    def quit(self):
        self.driver.quit()


if __name__ == "__main__":
    a = App()
    a.startappium()
    print('这是主线程的代码')

    time.sleep(10)
    print('想要停止运行')
    a.stopappium()
